import sys
from PySide6.QtWidgets import QWidget,QVBoxLayout,QTableWidget,QAbstractItemView,QHeaderView,QTableWidgetItem,QToolButton,QMenu,QMessageBox
from PySide6.QtGui import QAction,QBrush,QColor
import os
import redis

from BatRunWoker import Worker

class RedisWidget(QWidget):

    def __init__(self, main_ui):
        super().__init__()
        self.main_ui = main_ui
        self.logger=main_ui.logger
        self.config = main_ui.config

        host = self.config.get("redis", "host")
        port = self.config.get("redis", "port")
        self.pool = redis.ConnectionPool(host=host, port=int(port))
        self.setWindowTitle("Redis 数据库信息")
        layout = QVBoxLayout(self)
        self.base_dir = self.main_ui.base_dir

        self.table_widget = QTableWidget(self)
        self.table_widget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.table_widget.setRowCount(1)
        self.table_widget.setColumnCount(4)
        self.table_widget.setEditTriggers(
            QAbstractItemView.EditTrigger.NoEditTriggers)
        self.table_widget.setHorizontalHeaderLabels(
            ["地址", "端口", "连接状态", "操作"]
        )

        self.table_widget.setItem(0, 0, QTableWidgetItem(host))
        self.table_widget.setItem(0, 1, QTableWidgetItem(port))

        # 菜单工具按钮
        tool_button_menu = QToolButton(self)
        self.table_widget.setCellWidget(0, 3, tool_button_menu)
        tool_button_menu.setText("操作")
        tool_button_menu.setAutoRaise(True)

        # 以下是为tool_button_menu添加menu信息。
        menu = QMenu(tool_button_menu)

        ini_action = QAction("打开配置文件", menu)
        menu.addAction(ini_action)
        ini_action.triggered.connect(
            lambda: os.startfile(self.main_ui.cfg_file)
        )

        open_action = QAction("打开Redis客户端", menu)
        open_action.triggered.connect(self.openrdm)
        open_action.setData("OpenAction")
        menu.addAction(open_action)

        menu.addSeparator()
        Refresh_action = QAction("刷新", menu)
        menu.addAction(Refresh_action)
        Refresh_action.setData("IniAction")
        Refresh_action.triggered.connect(self.refresh_state)

        deltable_action = QAction("删除缓存", menu)
        deltable_action.setData("deltable_action")
        deltable_action.triggered.connect(self.drop_keys)
        menu.addAction(deltable_action)

        tool_button_menu.setMenu(menu)
        tool_button_menu.setPopupMode(QToolButton.InstantPopup)

        layout.addWidget(self.table_widget)
        self.setLayout(layout)
        self.refresh_state()
    def openrdm(self):
        try:
            path = self.config.get('redis', 'rdm')
            absolute_path = os.path.abspath(path)
            self.logger.log_info(f"路径{absolute_path}")
            os.startfile(absolute_path)
        except Exception as ex:
            self.logger.log_error(f"失败：{ex}")
    def open_ini(self, str_dir):
        os.startfile(str_dir)

    def drop_keys(self):
        reply = QMessageBox.warning(
            self,
            "确认",
            "此过程不可撤销，确定要批量删除缓存吗?",
            QMessageBox.Yes | QMessageBox.No,
            QMessageBox.No,
        )

        keyprefix = self.config.get("redis", "keyprefix")
        if reply == QMessageBox.Yes:
            try:
                with redis.Redis(connection_pool=self.pool) as p:
                    for key in p.scan_iter(f"{keyprefix}:*"):
                        p.delete(key)
                self.main_ui.logger.log_info(f"批量删除 {keyprefix} 前缀成功")
            except Exception as ex:
                self.main_ui.logger.log_error(f"批量删除 {keyprefix} 前缀失败：{ex}")
                self.main_ui.logger.log_info(f"您也可以打开客户端操作")
        else:
            self.main_ui.logger.log_info(f"取消操作")

    def refresh_state(self):
        self.main_ui.logger.log_info("获取redis连接状态")
        result = False
        try:
            with redis.Redis(connection_pool=self.pool) as p:
                info = p.info()["redis_version"]
                if info is not None:
                    self.main_ui.logger.log_info(f"redis_version {info}")
                    result = True
        except Exception as ex:
            self.main_ui.logger.log_error(ex)

        if result is True:
            item = QTableWidgetItem("正常")
            item.setBackground(QBrush(QColor(0, 255, 0)))
            self.table_widget.setItem(0, 2, item)
        else:
            item = QTableWidgetItem("错误")
            item.setBackground(QBrush(QColor(255, 0, 0)))
            self.table_widget.setItem(0, 2, item)


# if __name__ == "__main__":
#     app = QApplication(sys.argv)
#     widget = RedisWidget(main_ui=myMainWindow())
#     widget.resize(800, 600)
#     widget.show()
#     sys.exit(app.exec())
